<template>
  <el-upload
    class="upload-demo"
    :class="{ full: isFull }"
    :action="uploadAction"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="limit"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :file-list="fileList"
    :headers="uploadHeaders"
    :data="uploadData"
  >
    <el-button size="small" type="primary">点击上传</el-button>
  </el-upload>
</template>
<script>
export default {
  props: {
    limit: {
      type: [Number],
      default: 1
    },
    path: {
      type: [String],
      default: "sign"
    },
    value: {
      type: [String],
      default: ""
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    value: {
      handler: function(n) {
        if (!n) {
          return;
        }
        if (this.fileList.length) {
          return;
        }
        let arr = n.split(",");
        console.log(arr);
        arr.forEach(item => {
          console.log(item, "item");
          this.fileList.push({
            url: item,
            name: item
          });
        });
      },
      immediate: true
    }
  },
  computed: {
    isFull() {
      if (this.fileList.length >= this.limit) {
        return true;
      }
      return false;
    },
    apiConfig() {
      return this.$appConf.domain;
    },
    uploadData() {
      return {};
    },
    uploadHeaders() {
      return { token: window.sessionStorage.getItem("token") };
    },
    uploadAction() {
      return `${this.apiConfig.uploadUrl1}?path=${this.path}`;
    },
    uploadList() {
      let arr = [];
      this.fileList.forEach(element => {
        arr.push(element.url || element.response.value);
      });
      return arr.join(",");
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.$nextTick(() => {
        this.$emit("input", this.uploadList);
      });
      //   console.log(file, fileList);
    },
    handlePreview(file) {
      //   console.log(file);
      const imageValue = file.url || file.response.value;
      const imageUrl = `${this.apiConfig.image}/${imageValue}`;
      const token = this.uploadHeaders.token;
      const query = `url=${imageUrl}&token=${token}`;
      const openUrl = `${this.apiConfig.preFile}?${query}`;
      window.open(openUrl);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
      this.$nextTick(() => {
        this.$emit("input", this.uploadList);
      });
    },
    beforeRemove(files) {
      return true;
    }
  }
};
</script>
<style lang="scss" scoped>
.upload-demo /deep/ .el-upload-list__item-status-label {
  position: absolute;
}
.upload-demo.full /deep/ .el-upload {
  display: none;
}
</style>
